<template>
  <div class="order">
    <el-card>
      <!-- 面包屑导航 -->
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>订单管理</el-breadcrumb-item>
        <el-breadcrumb-item>订单列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 标题 -->
      <el-col class="title">
        <el-row>订单列表</el-row>
      </el-col>
      <!-- 表单 -->
      <el-form inline ref="queryFormRef" :model="queryForm">
        <el-row>
          <el-col :span="6">
            <!-- 订单号查询 -->
            <el-form-item label="订单号" prop="orderID">
              <el-input
                placeholder="订单号"
                v-model.number="queryForm.orderID"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- 配送方式查询 -->
            <el-form-item label="配送方式" prop="area">
              <el-select placeholder="配送方式" v-model="queryForm.area">
                <el-option label="全部" value="all"></el-option>
                <el-option label="到店自提" value="self"></el-option>
                <el-option label="同城配送" value="sameCity"></el-option>
                <el-option label="跨城配送" value="crossCity"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <!-- 下单日期 -->
            <el-form-item label="下单日期" prop="date">
              <el-date-picker
                v-model="queryForm.date"
                type="daterange"
                align="right"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <!-- 手机号查询 -->
            <el-form-item label="手机号" prop="phone">
              <el-input
                placeholder="手机号"
                v-model="queryForm.phone"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="10">
            <!-- 提交 -->
            <el-button type="primary" @click="submit">查询</el-button>
            <el-button @click="queryFormReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 按钮组 -->
      <el-row class="btn-group">
        <el-button-group>
          <el-button @click="changeAll">全部</el-button>

          <el-badge :value="paidNum" class="item" :max="99">
            <el-button @click="changeStatus('paid')">待支付</el-button>
          </el-badge>

          <el-badge :value="raisedNum" class="item" :max="99">
            <el-button @click="changeStatus('raised')">待自提</el-button>
          </el-badge>

          <el-badge :value="deliveredNum" class="item" :max="99">
            <el-button @click="changeStatus('delivered')">待配送</el-button>
          </el-badge>

          <el-button @click="changeStatus('received')">已收货</el-button>

          <el-button @click="changeStatus('refund')">售后退款</el-button>

          <el-button @click="changeStatus('cancel')">已取消</el-button>
        </el-button-group>
      </el-row>
      <!-- 表格数据 -->
      <div class="table">
        <el-table :data="orderTableList" style="width: 100%" border stripe>
          <el-table-column prop="orderID" label="订单号"></el-table-column>
          <el-table-column prop="goodsList" label="商品列表">
            <template slot-scope="scope">
              <el-tag
                class="goodsNameTag"
                :type="['success', 'warning', 'info', 'primary'][i]"
                v-for="(v, i) in scope.row.goodsList.goodsList"
                :key="i"
              >
                {{ v.goodsName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="下单时间"></el-table-column>
          <el-table-column prop="price" label="订单总金额">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}元</span>
            </template>
          </el-table-column>
          <el-table-column prop="area" label="配送方式">
            <!-- 'self', 'sameCity', 'crossCity' -->
            <template slot-scope="scope">
              <el-tag v-if="scope.row.areaName.areaName === 'self'"
                >用户自提</el-tag
              >
              <el-tag
                type="warning"
                v-if="scope.row.areaName.areaName === 'sameCity'"
                >同城配送</el-tag
              >
              <el-tag
                type="danger"
                v-if="scope.row.areaName.areaName === 'crossCity'"
                >跨城配送</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="address" label="收货地址/收货人">
            <template slot-scope="scope">
              <div>联系人: {{ scope.row.info.name }}</div>
              <div>联系电话: {{ scope.row.info.phone }}</div>
              <div>地址: {{ scope.row.info.address }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.status.status === 'paid'"
                >待支付</el-tag
              >
              <el-tag v-if="scope.row.status.status === 'raised'"
                >待自提</el-tag
              >
              <el-tag
                type="warning"
                v-if="scope.row.status.status === 'delivered'"
                >待配送</el-tag
              >
              <el-tag
                type="success"
                v-if="scope.row.status.status === 'received'"
                >已收货</el-tag
              >
              <el-tag type="danger" v-if="scope.row.status.status === 'refund'"
                >待退款</el-tag
              >
              <el-tag type="info" v-if="scope.row.status.status === 'cancel'"
                >已取消</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="170">
            <template slot-scope="scope">
              <!-- // 'paid', 待支付 // 'raised', 待自提 // 'delivered', 待配送 //
              'received', 已收货 // 'refund', 退款 // 'cancel, 取消 // 状态 -->
              <!-- 查看订单 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="查看订单"
                placement="top"
              >
                <el-button
                  icon="el-icon-search"
                  circle
                  @click="$router.push(`/orderDetail/${scope.row.orderID}`)"
                ></el-button>
              </el-tooltip>
              <!-- 待自提，确认自提 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="确认自提"
                placement="top"
              >
                <el-button
                  v-if="scope.row.status.status === 'raised'"
                  type="warning"
                  icon="el-icon-goods"
                  circle
                  @click="checkReceived(scope.row)"
                ></el-button>
              </el-tooltip>
              <!-- 待配送，确认配送 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="确认配送"
                placement="top"
              >
                <el-button
                  v-if="scope.row.status.status === 'delivered'"
                  type="warning"
                  icon="el-icon-check"
                  circle
                  @click="checkReceived(scope.row)"
                ></el-button>
              </el-tooltip>
              <!-- 申请退款 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="确认退款"
                placement="top"
              >
                <el-button
                  v-if="scope.row.status.status === 'refund'"
                  type="warning"
                  icon="el-icon-circle-close"
                  circle
                  @click="
                    $message({
                      message: '功能开发中',
                      type: 'warning'
                    })
                  "
                ></el-button>
              </el-tooltip>
              <!-- 取消订单 -->
              <el-tooltip
                v-if="
                  scope.row.status.status !== 'received' &&
                    scope.row.status.status !== 'cancel'
                "
                class="item"
                effect="dark"
                content="取消订单"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="cancelOrder(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="curPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 日期选择器
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 查询表单
      queryForm: {
        // 订单id
        orderID: '',
        // 配送区域
        area: 'all',
        // 日期选择
        date: '',
        // 手机号
        phone: ''
      },
      // 订单表格数据
      orderTableData:
        JSON.parse(window.localStorage.getItem('orderData')) || [],
      // 筛选后数据
      orderTableList: [],
      // 临时数据
      orderData: [],
      // 待支付数量，改成计算属性
      // paidNum: '99+',
      // 待自提数量，改为计算属性
      // raisedNum: '99+',
      // // 待配送数量，改为计算属性
      // deliveredNum: '99+',
      // // 数组总数量，改为计算属性
      // total: '99+',
      // 每页显示数量
      pageSize: 10,
      // 当前页
      curPage: 1,
      // 加载中
      loading: false
    }
  },
  methods: {
    // 重置表单
    queryFormReset() {
      this.$refs.queryFormRef.resetFields()
      this.orderData = this.orderTableData
      this.orderTableList = this.orderTableData.slice(0, this.pageSize)
    },
    // 显示全部数据
    changeAll() {
      this.orderData = this.orderTableData
      this.orderTableList = this.orderData.slice(0, this.pageSize)
    },
    // 更改数据显示
    changeStatus(status) {
      this.orderData = this.orderTableData.filter(item => {
        return item.status.status === status
      })
      this.orderTableList = this.orderData.slice(0, this.pageSize)
    },
    // 提交表单查询
    submit() {
      this.orderData = this.orderTableData
      const { date, orderID, phone, area } = this.queryForm
      if (area === 'all') {
        this.orderData = this.orderTableData
        this.orderTableList = this.orderData.slice(0, this.pageSize)
      }
      if (date !== '') {
        const beforDate = date[0]

        const afterDate = date[1]
        const arr = []

        this.orderData.forEach(item => {
          // console.log(item.date)
          const value = new Date(item.date)

          if (beforDate < value && value < afterDate) {
            arr.push(item)
          }
        })
        this.orderData = arr
      }
      if (orderID !== '') {
        const arr = []
        const orderIDstr = orderID.toString()
        this.orderData = this.orderData.forEach(item => {
          // console.log(item.orderID.toString().includes(orderIDstr))
          if (item.orderID.toString().includes(orderIDstr)) {
            arr.push(item)
          }
        })
        this.orderData = arr
        this.orderTableList = this.orderData.slice(0, this.pageSize)
      }
      if (phone !== '') {
        // const reg = /^1(3|4|5|6|7|8|9)\d{9}$/
        // console.log(phone)
        // console.log(!reg.test(phone))
        // if (!reg.test(phone)) {
        //   return this.$message({
        //     message: '请输入正确的手机号码',
        //     type: 'warning'
        //   })
        // }
        this.orderData = this.orderTableList.filter(item => {
          // console.log(item.info.phone)
          return item.info.phone.includes(phone)
        })
      }
      if (area !== 'all') {
        this.orderData = this.orderData.filter(item => {
          // console.log(item.areaName.areaName)
          return item.areaName.areaName === area
        })
      }
      // console.log(this.orderTableList, this.orderData)
      this.orderTableList = this.orderData.slice(0, this.pageSize)
    },
    // 更改显示数量
    handleSizeChange(value) {
      // console.log(value)
      const limt = value * (this.curPage - 1)
      this.pageSize = value
      const size = this.pageSize * this.curPage
      this.orderTableList = this.orderTableData.slice(limt, size)
    },
    // 更改当前页
    handleCurrentChange(value) {
      const limt = (value - 1) * this.pageSize
      const size = this.pageSize * value

      if (this.orderData.length !== 0) {
        this.orderTableList = this.orderData.slice(limt, size)
      }
      this.curPage = value
      // console.log(limt)
      this.orderTableList = this.orderTableData.slice(limt, size)
      // console.log(limt, size)
      console.log(this.orderTableList)
    },
    // 'raised', 待自提 // 'delivered', 待配送
    checkReceived(value) {
      let title = ''
      if (value.status.status === 'raised') {
        title = '是否确认用户提货?'
      }
      if (value.status.status === 'delivered') {
        title = '是否确认配送?'
      }
      this.$confirm(title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.orderTableData.findIndex(item => {
            return item.orderID === value.orderID
          })
          this.orderTableData[index].status.status = 'received'
          this.orderData = this.orderTableData
          this.orderTableList = this.orderData.slice(0, this.pageSize)
          window.localStorage.setItem(
            'orderData',
            JSON.stringify(this.orderTableData)
          )
          this.$message({
            type: 'success',
            message: '提货成功'
          })
        })
        .catch(() => {})
    },
    // 取消订单
    cancelOrder(value) {
      this.$confirm('是否取消订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.orderTableData.findIndex(item => {
            return item.orderID === value.orderID
          })
          this.orderTableData[index].status.status = 'cancel'
          this.orderData = this.orderTableData
          this.orderTableList = this.orderData.slice(0, this.pageSize)
          window.localStorage.setItem(
            'orderData',
            JSON.stringify(this.orderTableData)
          )
          this.$message({
            type: 'info',
            message: '取消订单成功'
          })
        })
        .catch(() => {})
    }
  },
  async created() {
    // if (this.orderTableData.length === 0) {
    //   const num = Random.integer(10, 200)
    //   const arr = []
    //   for (let i = 0; i < num; i++) {
    //     // 订单id
    //     const orderID = Random.integer(10000)
    //     // 商品列表
    //     const { goodsList } = mock({
    //       'goodsList|1-6': [
    //         {
    //           'goodsName|1': [
    //             '猪肉800g',
    //             '羊肉800g',
    //             '西瓜800g',
    //             '桃子800g',
    //             '苹果800g',
    //             '辣条800g'
    //           ]
    //         }
    //       ]
    //     })
    //     // 下单日期
    //     const date = Random.date('yyyy-MM-dd HH:mm')
    //     // 配送方式
    //     const {
    //       area: { areaName }
    //     } = mock({
    //       'area|1': {
    //         'areaName|1': ['self', 'sameCity', 'crossCity']
    //       }
    //     })
    //     // 配送地址
    //     const address = mock('@county(true)')
    //     // 电话
    //     const { phone } = mock({
    //       phone: /^1(3|4|5|6|7|8|9)\d{9}$/
    //     })
    //     const name = Random.cname()
    //     // 'paid', 待支付
    //     // 'raised', 待自提
    //     // 'delivered', 待配送
    //     // 'received', 已收货
    //     // 'refund', 退款
    //     // 'cancel, 取消
    //     // 状态
    //     const {
    //       status: { status }
    //     } = mock({
    //       'status|1': {
    //         'status|1': [
    //           'paid',
    //           'raised',
    //           'delivered',
    //           'received',
    //           'refund',
    //           'cancel'
    //         ]
    //       }
    //     })
    //     // 订单总金额
    //     const price = Random.float(10, 200, 2, 2)
    //     // console.log(orderID, goodsList, date, areaName, address, status)
    //     const tabData = {
    //       orderID,
    //       goodsList,
    //       date,
    //       areaName,
    //       info: {
    //         phone,
    //         name,
    //         address
    //       },
    //       status,
    //       price
    //     }

    //     arr.push(tabData)
    //   }
    //   this.orderTableData = arr
    //   window.localStorage.setItem(
    //     'orderData',
    //     JSON.stringify(this.orderTableData)
    //   )
    // }
    if (this.orderTableData.length === 0) {
      const { data } = await this.$http.get('tabData')
      console.log(data)
      this.orderTableData = data.tabData
      window.localStorage.setItem(
        'orderData',
        JSON.stringify(this.orderTableData)
      )
    }
    this.orderTableList = this.orderTableData.slice(0, this.pageSize)
    this.orderData = this.orderTableData
    // console.log(this.orderTableData)
  },
  computed: {
    // 待支付数量
    paidNum() {
      return this.orderData.filter(item => {
        return item.status.status === 'paid'
      }).length
    },
    // 待自提数量
    raisedNum() {
      return this.orderData.filter(item => {
        return item.status.status === 'raised'
      }).length
    },
    // 待配送数量
    deliveredNum() {
      return this.orderData.filter(item => {
        return item.status.status === 'delivered'
      }).length
    },
    // 数组总数量
    total() {
      return this.orderData.length
    }
  }
}
</script>

<style lang="less" scoped>
.order {
  min-width: 1260px;
  .title {
    margin: 20px;
  }
  .btn-group {
    margin-top: 20px;
    /deep/.el-badge__content {
      z-index: 2;
    }
  }
  .table {
    margin-top: 20px;
  }
  .goodsNameTag {
    margin: 5px;
  }
  /deep/.el-pagination {
    margin-top: 20px;
  }
}
</style>
